%% Aim
% Plot gaze heatmap

%% Setup
tic;
clc;
clear;
root_path = pwd; 
addpath(genpath(root_path));

nrole=2;
nblock=2;
ntrial=100;
nprice=10;
nlottery=10;

nchoice=2;
choice_label={'Buy','Not Buy'; 'Sell','Not Sell'};

role_label={'Buyer','Seller','Contrast'};
role_color_dark={[235/255 112/255 99/255],[106/255 142/255 208/255]}; 
role_color_median={[238/255 137/255 126/255],[144/255 171/255 220/255],[0.75 0.75 0.75]}; 
role_color_light={[243/255 171/255 163/255],[165/255 187/255 227/255]};

bias_label={'Val','Res','Val vs. Res'};
bias_color_median={[195/255 205/255 147/255],[192/255 173/255 203/255]}; 

attribute_label={'Price','Lottery'};
attribute_color={[91/255,155/255,213/255],[112/255,173/255,71/255],[166/255,166/255,166/255]}; % Price vs. Lottery

%% Load data
sub_data=readtable([root_path,'\data\subject\subject.csv']);
sub_beh_data=readtable([root_path,'\data\subject\subject_behavior.csv']);
beh_data=readtable([root_path,'\data\behavior\behavior.csv']);
eye_data=readtable([root_path,'\data\eye\eye.csv']);
gaze_trial_data=readtable([root_path,'\data\gaze\gaze_trial.csv']);
eye_trial_data=readtable([root_path,'\data\eye\eye_trial.csv']);
sub_ddm_data=readtable([root_path,'\data\subject\subject_ddm.csv']);
nsub=height(sub_data);

%% Concatenated data
sub_data = [sub_data, sub_beh_data(:,4:end), sub_ddm_data(:,4:end)];
trial_data = [beh_data, eye_trial_data(:,9:end), gaze_trial_data(:,9:end)];

%%










%% generate gaze data for each trial and each subject, save to a .mat file

for isub = 1:nsub
    for irole = 1:2
        
        edata=eye_data(eye_data.Subject==isub & eye_data.Role==irole,:);
        % remove invalid values: -1, 0, NaN
        edata(edata.GazeX<=0 | edata.GazeY<=0 | isnan(edata.GazeX) | isnan(edata.GazeY),:) = [];

       %% categorize x and y
        locations = [];
        for i = 1:height(edata)
            x = edata.GazeX(i);
            y = edata.GazeY(i);
            if y >= 275 && y <= 775
                % if fix is in the left square
                if x >= 160 && x <= 660
                    locations = [locations; -1];
                % if fix is in the center
                elseif x > 660 && x < 1020
                    locations = [locations; 0];
                % if fix is in the right square
                elseif x >= 1020 && x <= 1520
                    locations = [locations; 1];
                else
                    locations = [locations; 9];
                end
            else
                locations = [locations; 9];
            end
        end
        edata.Location = locations;
    
       %% find change indics of Location and Stimulus
        edata.DiffLocation=[NaN;diff(edata.Location)];
        edata.DiffStim=[NaN;diff(edata.StimulusName)];
        edata.Diff=abs(edata.DiffLocation)+abs(edata.DiffStim);
        idx=find(edata.Diff~=0);
    
       %% removing gaze<50 ms
        edata.Remove(:)=0;
        for i=1:length(idx)-1
            if edata.TimeSignal(idx(i+1))-edata.TimeSignal(idx(i))<50
               edata.Remove(idx(i):idx(i+1)-1)=1;
            end
        end
        edata=edata(edata.Remove==0,:);
    
       %% keep only options
        edata=edata(edata.StimulusName>100,:);

       %% keep gaze at price or lottery
        edata=edata(edata.Location==1 | edata.Location==-1,:);
    
       %% Flip X coordinate when price is on the right
        if edata.PricePosition(1)==2
           edata.GazeX=1680-edata.GazeX;
        end    
    
       %% generate heatmap for each trial, set price on left and lottery on right
        % go through every trial
        edata.DiffStimOnly=[NaN;diff(edata.StimulusName)];
        idx=find(edata.DiffStimOnly~=0);
        for i=1:length(idx)
            iprice = floor(edata.StimulusName(idx(i))/1000);
            ilottery = mod(edata.StimulusName(idx(i)),1000)/2;          
            wdata=edata(edata.StimulusName==edata.StimulusName(idx(i)),:);
            gaze_trial_map{iprice,ilottery}=zeros(1050,1680);
            for j=1:height(wdata)
                gaze_trial_map{iprice,ilottery}(round(wdata.GazeY(j)),round(wdata.GazeX(j)))=gaze_trial_map{iprice,ilottery}(round(wdata.GazeY(j)),round(wdata.GazeX(j)))+1;
            end
            gaze_trial_map{iprice,ilottery}=gaze_trial_map{iprice,ilottery}./height(wdata);
        end
        save([root_path, '\figure\gaze\duration\heatmap\s',num2str(isub),'_r',num2str(irole),'_gaze_trial_map.mat'], 'gaze_trial_map');
    
    end
end

%% Generate gaze map for the group: across trials

tdur_group={zeros(1050,1680);zeros(1050,1680)};
figure('Renderer', 'painters', 'Position', [10 10 1600 350]);
% across accept and reject trials
for irole=1:nrole
    ax=subplot(1,2,irole);
    count=0;
    for isub=1:nsub
            tdata=trial_data(trial_data.Subject==isub & trial_data.Role==irole & trial_data.ValidGaze==1,:);
            gdata=load([root_path,'\figure\gaze\duration\heatmap\s',num2str(isub),'_r',num2str(irole),'_gaze_trial_map.mat']);
            for t=1:height(tdata)
                if ~isempty(gdata.gaze_trial_map{tdata.Price(t), tdata.Lottery(t)./2})
                    tdur_group{irole}=tdur_group{irole}+gdata.gaze_trial_map{tdata.Price(t), tdata.Lottery(t)./2};
                    count=count+1;
                end
            end
    end
    tdur_mean_group{irole}=tdur_group{irole}./count;
    imagesc(tdur_mean_group{irole});
    colormap hot;     
    colorbar;
    caxis([0 0.00007]);
    %colorbar;
    rectangle('Position',[160 275 500 500],'EdgeColor',[0.4 0.4 0.4],'FaceColor','none','LineStyle','--','LineWidth',1);
    rectangle('Position',[1020 275 500 500],'EdgeColor',[0.4 0.4 0.4],'FaceColor','none','LineStyle','--','LineWidth',1);
    title(role_label{irole});    
end
print(1, '-dtiff', [root_path,'\figure\gaze\duration\heatmap\group_gaze_duration_across_trials.tif'], '-r200');
hold off;
close;

%% 
toc;
